package com.project.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器类
 */
public class Server {

    public Server(){
        try {
            //开启服务器，并开放8088端口
            ServerSocket serverSocket = new ServerSocket(8088);

            while(true){
                //监听端口，如果有客户端连接到服务器，将连接信息封装成socket对象
                Socket socket = serverSocket.accept();
                //从socket中得到读取流，用于读取客户端发送的数据
                InputStream in = socket.getInputStream();
                //从socket中得到写入流，用于将数据发送给客户端
                OutputStream out = socket.getOutputStream();

                byte[] by = new byte[1024];
                //将读取流中的数据，读取到byte数组
                in.read(by);
                String str = new String(by);
                System.out.println("客户端发送："+str);

                //发送数据到客户端
                out.write("欢迎光临".getBytes());
                out.flush();

                //关闭流
                out.close();
                in.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Server();
    }
}
